package net.bbtang.website.controller;



import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bbtang.website.pojo.UserAccountNoDTO;
import net.bbtang.website.pojo.UserDTO;
import net.bbtang.website.pojo.UserSmsDTO;
import net.bbtang.website.service.UniversityService;
import net.bbtang.website.service.UserAccountService;
import net.bbtang.website.service.UserInfoService;
import net.bbtang.website.utils.ConstantsStatus;
import net.bbtang.website.utils.LoginConstantsStatus;
import net.bbtang.website.utils.StatusCode;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/")
public class LoginApiController {
	@Autowired
	UserInfoService userInfoService;
	@Autowired
	UserAccountService userAccountService;
	@Autowired
	UniversityService universityService;
	
	
	private static final Logger logger = Logger.getLogger(LoginApiController.class); 
	
	/**三方授权校验是否注册
	 @api {post} /checkToken 三方授权校验是否注册
	 
	 @apiParam {string} accessToken 用户token 必填

	 @apiSuccess {boolean} flag 请求状态，码状态   成功：true 失败：false
	 @apiSuccess {String} num 状态码值
	 @apiSuccess {String} detailMsg 状态码详细值
	 @apiSuccess {Object} data 返回数据
	
	 @apiParamExample {json} 请求参数Demo:
	 {
		"accessToken":"12323423424",
	}

	@apiSuccessExample {json} 请求成功结果Demo:
	{
		  "number": "2003",//未注册
		  "flag": true,
	}
	
	{
	    "number": "2004",//已经注册
	    "flag": false,
	    "detailMsg": "已经注册",
	    "data": {
	        "id": 1,
	        "userName": "张小盒",
	        "sex": 0,
	        "headImage": "www.baidu.com",
	        "studentCardMain": "www.baidu.com",
	        "studentCardBack": "www.baidu.com",
	        "telphone": "1888888888",
	        "dormitoryNo": "1-2-301",
	        "wechatNo": "12345",
	        "qqNo": "54321",
	        "personalSignature": "好孩子",
	        "universityId": 2,
	        "changeUniversityNum": 4,
	        "isRealName": 1,
	        "isGroup": 1,
	        "qrcode": "www",
	        "openId": "qweqweqweqwe",
	        "createTime": 1492176561000,
	        "updateTime": 1492438657000
	    }
	}

	@apiErrorExample {json} 请求成功得异常结果
	HTTP/1.1 5000 error
	{
	  "number": "5000",
	  "flag": false,
	  "detailMsg": "token校验失败"
	}

	@apiErrorExample  请求参数异常
		HTTP/1.1 400
	@apiErrorExample  请求数据类型异常
	HTTP/1.1 415
	@author wxw
	 */
	@RequestMapping(value = "/checkToken", method = RequestMethod.POST)
	@ResponseBody
	public Object checkToken(@RequestBody Object body,HttpServletRequest request,HttpServletResponse response) {
		StatusCode<Object> sc=new StatusCode<Object>(ConstantsStatus.SC2000);
		try {
			JSONObject jb = JSONObject.fromObject(body);
			if(!jb.containsKey("accessToken")){
				sc.codes(ConstantsStatus.SC5000);
				sc.setDetailMsg("accessToken is null");
				return sc;
				
			}
			String accessToken = jb.getString("accessToken");
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userAccountToken", accessToken);
			UserAccountNoDTO account = userAccountService.getUserAccount(map);
			if(account == null){
				sc.setFlag(true);
				sc.codes(ConstantsStatus.SC2003);
				sc.setDetailMsg("未注册");
			}else{
				Map<String,Object> mapUser =new HashMap<String, Object>();
				map.put("userId", account.getUserId());
				List<UserDTO> userList = userInfoService.getUserInfoById(mapUser);
				if(userList != null && userList.size() > 0){
					sc.setFlag(true);
					sc.setData(userList.get(0));
				}else{
					sc.codes(ConstantsStatus.SC5000);
					sc.setDetailMsg("查询用户信息失败！");
				}
				sc.codes(ConstantsStatus.SC2004);
				sc.setDetailMsg("已经注册");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			sc.codes(ConstantsStatus.SC5000);
			sc.setDetailMsg("token校验失败");
		}
		
		return sc;
	
	}
	
	
	
	
	/**登录
	 @api {post} /login 注册\登录接口(根据返回参数判断手机号是否存在来判断初始授权或者二次授权)
	 
	 @apiParam {int} accountType 账号类型(0:普通登录  1微信：   2：微博   3：qq) 必填
	 @apiParam {String} telphone 手机号 必填
	 @apiParam {String} code 验证码
	 @apiParam {String} accessToken 三方获取token 非必填（普通手机号登录无此字段）
	 @apiParam {String} refreshToken 三方刷新token 非必填 （普通手机号登录无此字段）
	 @apiParam {String} openId 三方登录用户唯一标识  非必填 （普通手机号登录无此字段）

	 @apiSuccess {boolean} flag 请求状态，码状态   成功：true 失败：false
	 @apiSuccess {String} num 状态码值
	 @apiSuccess {String} detailMsg 状态码详细值
	 @apiSuccess {Object} data 返回数据
	
	 @apiParamExample {json} 请求参数Demo:
	 {
		"accountType":1,
		"telphone":"15020000000",
		"accessToken":"ASDASD-ASDASDA",
		"refreshToken":"ASDASD-ASDASDA",
		"openId":"ASDASD-ASDASDA"，
		"code":"1231"
	}

	@apiSuccessExample {json} 请求成功结果Demo:
	{
	    "number": "2000",
	    "flag": true,
	    "data":
	    {
	        "id": 4,
	        "telphone": "15020000000",
	        "userAccount":
	        {
	            "id": 1,
	            "userId": 1,
	            "userAccountType": 1,
	            "userAccountToken": "ASDASD-ASDASDA",
	            "refreshToken": "ASDASD-ASDASDA"
	        }
	    }
	}

	@apiErrorExample {json} 请求成功得异常结果
	HTTP/1.1 5000 error
	{
	  "number": "5000",
	  "flag": false,
	  "detailMsg": "登录异常"
	}
	{
	  "number": "5001",
	  "flag": false,
	  "detailMsg": "短信验证码错误"
	}
    {
        "number": "5002",
        "flag": false,
        "detailMsg": "验证码过期！"
    }



	@apiErrorExample  请求参数异常
		HTTP/1.1 400
	@apiErrorExample  请求数据类型异常
	HTTP/1.1 415
	@author wxw
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Object initOrder(@RequestBody Object body,HttpServletRequest request,HttpServletResponse response) {
		StatusCode<Object> sc=new StatusCode<Object>(ConstantsStatus.SC2000);
		UserDTO user = new UserDTO();
		UserAccountNoDTO userAccount = new UserAccountNoDTO();
		try {
			JSONObject jb = JSONObject.fromObject(body);
			Integer accountType = jb.getInt("accountType");
			String telphone = null;
			String accessToken = null;//获取用户信息
			String refreshToken = null;
			String openId = null;//用户唯一标示
			Map<String,Object> map = new HashMap<String,Object>();
			if(!jb.containsKey("accountType")){
				sc.codes(ConstantsStatus.SC5000);
				sc.setDetailMsg("accountType is null");
				return sc;
				
			}
			if(!jb.containsKey("openId") && !jb.containsKey("telphone")&& !jb.containsKey("accountType")){
				sc.codes(ConstantsStatus.SC5000);
				sc.setDetailMsg("openId or telphone is null");
				return sc;
				
			}
			if(accountType == LoginConstantsStatus.NORMAL){
				telphone = jb.getString("telphone");
				if(!jb.containsKey("telphone")){
					sc.codes(ConstantsStatus.SC5000);
					sc.setDetailMsg("手机号登陆：telphone is null");
					return sc;
				}
				//根据手机号查询是否存在用户信息
				map.put("telphone", telphone);
				
			}else{
				accessToken = jb.getString("accessToken");//获取用户信息
				refreshToken = jb.getString("refreshToken");
				openId = jb.getString("openId");//用户唯一标示
				if(!jb.containsKey("openId")){
					sc.codes(ConstantsStatus.SC5000);
					sc.setDetailMsg("三方授权登陆：openId is null");
					return sc;
				}
				//根据openId查询是否存在用户信息
				map.put("openId", openId);
				
			}
			user.setTelphone(telphone);
			userAccount.setUserAccountToken(accessToken);
			userAccount.setUserAccountType(accountType);
			userAccount.setRefreshToken(refreshToken);
			user.setUserAccount(userAccount);
			user.setOpenId(openId);
			//校验注册码是否正确
			if(!jb.containsKey("code")){
				sc.codes(ConstantsStatus.SC5000);
				sc.setDetailMsg("短信：code is null");
				return sc;
			}
			UserSmsDTO sms = userInfoService.getPhoneCodeByNum(telphone,jb.getString("code"));
			if(sms == null){
				sc.codes(ConstantsStatus.SC5001);
				sc.setDetailMsg("验证码错误！");
				return sc;
			}else{
				Calendar codeTime = Calendar.getInstance();
				codeTime.setTime(sms.getCreateDate());
				codeTime.add(Calendar.MINUTE, 10);
				Calendar nowTime = Calendar.getInstance();
				nowTime.setTime(new Date());
				if(codeTime.getTimeInMillis() < nowTime.getTimeInMillis()){
					sc.codes(ConstantsStatus.SC5002);
					sc.setDetailMsg("验证码过期！");
					return sc;
				}
			}
			
			List<UserDTO> userSearch = userInfoService.getUserInfoById(map);
			if(userSearch != null && userSearch.size() > 0){
				userInfoService.updateUserInfo(user);
				sc.codes(ConstantsStatus.SC2004);
				sc.setDetailMsg("登录成功");
			}else{
				userInfoService.addUserInfo(user);
				sc.codes(ConstantsStatus.SC2003);
				sc.setDetailMsg("注册成功");
			}
			
			sc.setData(user);//根据返回参数判断手机号是否存在来判断初始授权或者二次授权
			sc.setFlag(true);
		} catch (Exception e) {
			e.printStackTrace();
			sc.codes(ConstantsStatus.SC5000);
			sc.setDetailMsg("登录异常");
		}
		
		return sc;
	
	}
	
	

	/**获取手机验证码
	 @api {post} /getPhoneCode 获取手机验证码接口
	 
	 @apiParam {String} telphone 手机号 必填

	 @apiSuccess {boolean} flag 请求状态，码状态   成功：true 失败：false
	 @apiSuccess {String} num 状态码值
	 @apiSuccess {String} detailMsg 状态码详细值
	 @apiSuccess {Object} data 返回数据
	
	 @apiParamExample {json} 请求参数Demo:
	{
	"telphone":"18502234771"
	}
	@apiSuccessExample {json} 请求成功结果Demo:
	{
	    "number": "2000",
	    "flag": true,
	    "data": {
	        "code": "044184"
	    }
	}

	@apiErrorExample {json} 请求成功得异常结果
	HTTP/1.1 5000 error
	{
	  "number": "5000",
	  "flag": false,
	  "detailMsg": "获取手机验证码异常"
	}

	@apiErrorExample  请求参数异常
		HTTP/1.1 400
	@apiErrorExample  请求数据类型异常
	HTTP/1.1 415
	@author wxw
	 */
	@RequestMapping(value = "/getPhoneCode", method = RequestMethod.POST)
	@ResponseBody
	public Object getPhoneCode(@RequestBody Object body,HttpServletRequest request,HttpServletResponse response) {
		System.out.print(body.toString()+"<=======");
		StatusCode<Object> sc=new StatusCode<Object>(ConstantsStatus.SC2000);
		try {
			JSONObject jb = JSONObject.fromObject(body);
			String telphone = jb.getString("telphone");
			String code = userInfoService.getPhoneCode(telphone);
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("code", code);
			sc.setData(map);
			sc.setFlag(true);
		} catch (Exception e) {
			e.printStackTrace();
			sc.setFlag(false);
			sc.codes(ConstantsStatus.SC5000);
			sc.setDetailMsg("获取手机验证码异常");
		}
		
		
		return sc;
	
	}
	
	
	
	/**修改手机号
	 @api {post} /updatePhone 修改手机号
	 
	 @apiParam {int} userId 用户id 必填
	 @apiParam {String} telphone 申请人组建小组成员人数 必填
	 @apiParam {String} code 用户id 必填

	 @apiSuccess {boolean} flag 请求状态，码状态   成功：true 失败：false
	 @apiSuccess {String} num 状态码值
	 @apiSuccess {String} detailMsg 状态码详细值
	 @apiSuccess {Object} data 返回数据
	
	 @apiParamExample {json} 请求参数Demo:
	 {
		"userId":1,
		"telphone":15022222222,
		"code":"8239"
	}

	@apiSuccessExample {json} 请求成功结果Demo:
	{
	    "number": "2000",
	    "flag": true
	}

	@apiErrorExample {json} 请求成功得异常结果
	HTTP/1.1 5000 error
	{
	  "number": "5000",
	  "flag": false,
	  "detailMsg": "修改手机号异常"
	}

	@apiErrorExample  请求参数异常
		HTTP/1.1 400
	@apiErrorExample  请求数据类型异常
	HTTP/1.1 415
	@author wxw
	 */
	@RequestMapping(value = "/updatePhone", method = RequestMethod.POST)
	@ResponseBody
	public Object getOrderInfoList(@RequestBody Object body,HttpServletRequest request,HttpServletResponse response) {
		StatusCode<Object> sc=new StatusCode<Object>(ConstantsStatus.SC2000);
		UserDTO user = new UserDTO();
		try {
			JSONObject jb = JSONObject.fromObject(body);
			String changePhone = jb.getString("telphone");
			String code = jb.getString("code");
			Integer userId = jb.getInt("userId");
			//校验验证码是否正确
			UserSmsDTO sms = userInfoService.getPhoneCodeByNum(changePhone,jb.getString("code"));
			if(sms == null){
				sc.codes(ConstantsStatus.SC5001);
				sc.setDetailMsg("验证码错误！");
				return sc;
			}else{
				Calendar codeTime = Calendar.getInstance();
				codeTime.setTime(sms.getCreateDate());
				codeTime.add(Calendar.MINUTE, 10);
				Calendar nowTime = Calendar.getInstance();
				nowTime.setTime(new Date());
				if(codeTime.getTimeInMillis() < nowTime.getTimeInMillis()){
					sc.codes(ConstantsStatus.SC5002);
					sc.setDetailMsg("验证码过期！");
					return sc;
				}
			}
			
			
			user.setTelphone(changePhone);
			user.setId(userId);
			//查询手机号是否存在
			Map<String,Object> map =new HashMap<String,Object>();
			map.put("userId", userId);
			map.put("telphone", changePhone);
			userInfoService.updateUserInfo(user);
			sc.setFlag(true);
			
		} catch (Exception e) {
			e.printStackTrace();
			sc.codes(ConstantsStatus.SC5000);
			sc.setDetailMsg("修改手机号异常");
		}
		
		
		return sc;
	
	}
	
	/**修改学校
	 @api {post} /changeSchool 修改学校
	 
	 @apiParam {int} userId 用户id 必填
	 @apiParam {int} universityId 学校id 必填

	 @apiSuccess {boolean} flag 请求状态，码状态   成功：true 失败：false
	 @apiSuccess {String} num 状态码值
	 @apiSuccess {String} detailMsg 状态码详细值
	 @apiSuccess {Object} data 返回数据
	
	 @apiParamExample {json} 请求参数Demo:
	 {
		"userId":1,
		"universityId":1
	}

	@apiSuccessExample {json} 请求成功结果Demo:
	{
	    "number": "2000",
	    "flag": true	
	}

	@apiErrorExample {json} 请求成功得异常结果
	HTTP/1.1 5000 error
	{
	    "number": "5000",
	    "flag": false,
	    "detailMsg": "修改学校超过3次"
	}

	@apiErrorExample  请求参数异常
		HTTP/1.1 400
	@apiErrorExample  请求数据类型异常
	HTTP/1.1 415
	@author wxw
	 */
	@RequestMapping(value = "/changeSchool", method = RequestMethod.POST)
	@ResponseBody
	public Object changeSchool(@RequestBody Object body,HttpServletRequest request,HttpServletResponse response) {
		StatusCode<Object> sc=new StatusCode<Object>(ConstantsStatus.SC2000);
		UserDTO user = new UserDTO();
		try {
			JSONObject jb = JSONObject.fromObject(body);
			Integer universityId = jb.getInt("universityId");
			Integer userId = jb.getInt("userId");
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", userId);
			UserDTO userinfo = userInfoService.getUserInfoById(map).get(0);
			if(userinfo.getChangeUniversityNum() > 3){
				user.setUniversityId(userinfo.getUniversityId());
				sc.codes(ConstantsStatus.SC5000);
				sc.setDetailMsg("修改学校超过3次");
				return sc;
			}else{
				user.setChangeUniversityNum(userinfo.getChangeUniversityNum()+1);
				user.setUniversityId(universityId);
			}
			
			user.setId(userId);
			userInfoService.updateUserInfo(user);
			sc.setFlag(true);
			
		} catch (Exception e) {
			e.printStackTrace();
			sc.codes(ConstantsStatus.SC5000);
			sc.setDetailMsg("修改学校异常");
		}
		return sc;
	
	}
	
	/**获取所有已开通学校
	 @api {get} /getAllSchool 获取所有已开通学校
	 

	 @apiSuccess {boolean} flag 请求状态，码状态   成功：true 失败：false
	 @apiSuccess {String} num 状态码值
	 @apiSuccess {String} detailMsg 状态码详细值
	 @apiSuccess {Object} data 返回数据
	

	@apiSuccessExample {json} 请求成功结果Demo:
	{
	    "number": "2000",
	    "flag": true,
	    "data": [
	        {
	            "id": 1,
	            "universityName": "天津科技大学(河西校区)",
	            "universityInCity": 1,
	            "remarks": "备注",
	            "createTime": 1494849642000,
	            "updateTime": 1494849645000
	        },
	        {
	            "id": 2,
	            "universityName": "天津科技大学(泰达校区)",
	            "universityInCity": 1,
	            "remarks": "备注",
	            "createTime": 1494849673000,
	            "updateTime": 1494849676000
	        },
	        {
	            "id": 3,
	            "universityName": "天津商业大学",
	            "universityInCity": 1,
	            "remarks": "备注",
	            "createTime": 1494849695000,
	            "updateTime": 1494849697000
	        }
	    ]
	}

	@apiErrorExample {json} 请求成功得异常结果
	HTTP/1.1 5000 error
	{
	    "number": "5000",
	    "flag": false,
	    "detailMsg": "获取学校异常"
	}

	@apiErrorExample  请求参数异常
		HTTP/1.1 400
	@apiErrorExample  请求数据类型异常
	HTTP/1.1 415
	@author wxw
	 */
	@RequestMapping(value = "/getAllSchool", method = RequestMethod.GET)
	@ResponseBody
	public Object getAllSchool(HttpServletRequest request,HttpServletResponse response) {
		StatusCode<Object> sc=new StatusCode<Object>(ConstantsStatus.SC2000);
		try {
			sc.setData(universityService.getAllSchool());
			sc.setFlag(true);
			
		} catch (Exception e) {
			e.printStackTrace();
			sc.codes(ConstantsStatus.SC5000);
			sc.setDetailMsg("获取学校异常");
		}
		return sc;
	
	}
	
	/**完善个人信息
	 @api {post} /improveInfo 完善个人信息
	 
	 @apiParam {String} userName 用户名 必填
	 @apiParam {int} userId 用户id） 必填
	 @apiParam {int} sex 性别（0：女 1：男） 必填
	 @apiParam {String} headImage 头像 必填
	 @apiParam {String} studentCardMain 学生证正面 必填
	 @apiParam {String} studentCardBack 学生证背面 必填
	 @apiParam {String} dormitoryNo 宿舍号 必填
	 @apiParam {String} wechatNo 微信号 非必填
	 @apiParam {String} qqNo qq号 非必填
	 @apiParam {String} personalSignature 个人签名 非必填
	 @apiParam {int} universityId 学校 必填

	 @apiSuccess {boolean} flag 请求状态，码状态   成功：true 失败：false
	 @apiSuccess {String} num 状态码值
	 @apiSuccess {String} detailMsg 状态码详细值
	 @apiSuccess {Object} data 返回数据
	
	 @apiParamExample {json} 请求参数Demo:
	 {
		"userName":"张三",
		"sex":0,
		"headImage":"www.baidu.com",
		"studentCardMain":"www.zhengmian.com",
		"studentCardBack":"www.beimian.com",
		"dormitoryNo":"1-2-201",
		"wechatNo":"1111111",
		"qqNo":"2222222",
		"personalSignature":"个人优势",
		"universityId":"1"
	}

	@apiSuccessExample {json} 请求成功结果Demo:
	{
	    "number": "2000",
	    "flag": true	
	}

	@apiErrorExample {json} 请求成功得异常结果
	HTTP/1.1 5000 error
	{
	  "number": "5000",
	  "flag": false,
	  "detailMsg": "登录异常"
	}

	@apiErrorExample  请求参数异常
		HTTP/1.1 400
	@apiErrorExample  请求数据类型异常
	HTTP/1.1 415
	@author wxw
	 */
	@RequestMapping(value = "/improveInfo", method = RequestMethod.POST)
	@ResponseBody
	public Object improveInfo(@RequestBody Object body,HttpServletRequest request,HttpServletResponse response) {
		StatusCode<Object> sc=new StatusCode<Object>(ConstantsStatus.SC2000);
		try {
			JSONObject jb = JSONObject.fromObject(body);
			UserDTO userDTO = (UserDTO)JSONObject.toBean(jb, UserDTO.class);
			
			//根据userId查询用户信息
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", jb.getInt("userId"));
			List<UserDTO> userList = userInfoService.getUserInfoById(map);
			if(userList == null || userList.size() == 0){
				sc.codes(ConstantsStatus.SC5000);
				sc.setDetailMsg("查无此人");
				return sc;
			}else{
				UserDTO userDTOSer = userList.get(0);
				if((userDTO.getUniversityId() == null && userDTOSer.getUniversityId() == null)||
						(userDTO.getDormitoryNo() == null && userDTOSer.getDormitoryNo() == null)||
						(userDTO.getHeadImage() == null && userDTOSer.getHeadImage() == null)||
						(userDTO.getPersonalSignature() == null && userDTOSer.getPersonalSignature() == null)||
						(userDTO.getSex() == null && userDTOSer.getSex() == null)||
						(userDTO.getStudentCardBack() == null && userDTOSer.getStudentCardBack() == null)||
						(userDTO.getStudentCardMain() == null && userDTOSer.getStudentCardMain() == null)||
						(userDTO.getTelphone() == null && userDTOSer.getTelphone() == null)||
						(userDTO.getUserName() == null && userDTOSer.getUserName() == null)){
					userDTO.setIsRealName(LoginConstantsStatus.AUTHENTICATION_NO);
					
				}else{
					userDTO.setIsRealName(LoginConstantsStatus.AUTHENTICATION_YES);
				}
			}
			
			userInfoService.updateUserInfo(userDTO);
			
			sc.setFlag(true);
			
		} catch (Exception e) {
			e.printStackTrace();
			sc.codes(ConstantsStatus.SC5000);
			sc.setDetailMsg("完善信息异常");
		}
		return sc;
	
	}
	
	
}
